package com.zx.mes.hyl.utils;


import com.zx.mes.hyl.entity.Jwt;
import com.zx.mes.hyl.entity.SysUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

/**
 * 对第三方插件再做进一步封装
 * 1.生成token
 * 2.解析token
 * 3.得到token中的用户等相关信息
 * @author hyl
 * @date 2017-12-16
 */
public class JWTHelper {
    private static RsaKeyHelper rsaKeyHelper = new RsaKeyHelper();
    /**
     * 密钥加密token  生成token
     *
     * @param  jwt jwt
     * @param priKeyPath priKeyPath
     * @param expire 超时设置
     * @return String
     * @throws Exception Exception
     */
    public static String generateToken(Jwt jwt, String priKeyPath, int expire) throws Exception {
        String compactJws = Jwts.builder()
                .setSubject(jwt.getName())
                .claim("id", jwt.getId())
                .setExpiration(DateTime.now().plusSeconds(expire).toDate())
                .signWith(SignatureAlgorithm.RS256, rsaKeyHelper.getPrivateKey(priKeyPath))
                .compact();
        return compactJws;
    }

    /**
     * 公钥解析token
     *
     * @param token token
     * @return Jws Jws
     * @throws Exception Exception
     */
    public static Jws<Claims> parserToken(String token, String pubKeyPath) throws Exception {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(rsaKeyHelper.getPublicKey(pubKeyPath)).parseClaimsJws(token);
        return claimsJws;
    }

    /**
     * 获取token中的用户信息
     *
     * @param token token
     * @param pubKeyPath pubKeyPath
     * @return JWTInfoI
     * @throws Exception Exception
     */
    public  SysUser getInfoFromToken(String token, String pubKeyPath) throws Exception {
        Jws<Claims> claimsJws = parserToken(token, pubKeyPath);
        Claims body = claimsJws.getBody();
        // todo
//        return new JwtInfo( body.getSubject(), StringHelper.getObjectValue(body.get(CommonConstants.JWT_KEY_USER_ID)), StringHelper.getObjectValue(body.get(CommonConstants.JWT_KEY_NAME)));
        return null;
    }

}
